package com.shujia.spark.stream

import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}
import org.apache.spark.streaming.{Duration, Durations, StreamingContext}
import org.apache.spark.{SparkConf, SparkContext}

object Demo1WordCount {
  def main(args: Array[String]): Unit = {
    /**
     * 1、创建spark streaming环境
     *
     */

    val conf = new SparkConf()
    conf.setMaster("local[2]")
    conf.setAppName("stream")

    val sc = new SparkContext(conf)

    val ssc = new StreamingContext(sc, Durations.seconds(5))

    /**
     * 安装
     * yum install nc
     * 使用nc -lk 8888模拟实时数据源
     */
    /**
     * 从socket中读取数据构建一个Stream
     * Stream：和DF类似，底层都是RDD
     */

    val linesDS: ReceiverInputDStream[String] = ssc.socketTextStream("master", 8888)

    val wordsDS: DStream[String] = linesDS.flatMap(_.split(","))

    val kvDS: DStream[(String, Int)] = wordsDS.map((_, 1))

    /**
     * reduceByKey: 无状态的算子，只能再当前批次做统计
     */
    val countDS: DStream[(String, Int)] = kvDS.reduceByKey(_ + _)

    countDS.print()


    /**
     * 启动spark streaming
     */
    ssc.start()
    ssc.awaitTermination()
    ssc.stop()


  }

}
